﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Hjp.FrameWork.Common;
using Wjtour.Domain;
using System.IO;
using System.Reflection;
using org.in2bits.MyXls;
using Wjtour.BLL;

namespace Wjtour.Web.Admin
{
    public class BasePage : System.Web.UI.Page
    {
        private static Dictionary<string, Wjtour.Domain.menu> pathMenuMap = new Dictionary<string, Wjtour.Domain.menu>();
        private static List<Wjtour.Domain.menu> _menus = new List<Domain.menu>();

        /// <summary>
        /// 当前登录员工
        /// </summary>
        public Wjtour.Domain.sysadmin CurrentUser
        {
            get
            {
                return Session["CurrentUser"] as Wjtour.Domain.sysadmin;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public Dictionary<string, Wjtour.Domain.menu> PathMenus
        {
            get { return pathMenuMap; }
        }

        protected string PagerHtml
        {
            get;
            set;
        }

        /// <summary>
        /// 当前功能
        /// </summary>
        public Wjtour.Domain.menu CurrentFun
        {
            get
            {
                string type = Request["type"];
                string path = HttpContext.Current.Request.RawUrl.Substring(7);
                if (path.IndexOf("?") >= 0)
                {
                    path = path.Split('?')[0];
                }
                if (!string.IsNullOrEmpty(type))
                {
                    path += "?type=" + type;
                }
                if (pathMenuMap.ContainsKey(path))
                {
                    return pathMenuMap[path];
                }
                return new Domain.menu();
            }
        }

        public List<Wjtour.Domain.menu> Menus
        {
            get
            {
                return _menus;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string GetUploadDirectory(string rootdir, string tag, out string imgpath)
        {
            string dir = Server.MapPath(rootdir) + tag + "\\" + DateTime.Now.ToString("yyyy-MM-dd");
            imgpath = rootdir.Replace('\\', '/') + tag + "/" + DateTime.Now.ToString("yyyy-MM-dd");
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            return dir;
        }

        public string GetFileName(string type)
        {
            if (type == "guid")
                return Guid.NewGuid().ToString();
            else
                return string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), DateTime.Now.Millisecond);
        }
        /// <summary>
        /// 检查文件是否允许上传
        /// </summary>
        /// <param name="fileExtension">文件扩展名</param>
        /// <param name="allowUploadType">返回允许上传的文件类型</param>
        /// <returns></returns>
        public bool CheckFileAllowUpload(string fileExtension, out string allowUploadType)
        {
            string filetype = ConfigurationManager.AppSettings["AllowUploadFileType"];
            if (string.IsNullOrWhiteSpace(filetype))
                filetype = "jpg,jpeg,gif";
            allowUploadType = filetype;
            if (string.IsNullOrEmpty(filetype)) return false;
            if (filetype.IndexOf(',') > -1)
            {
                string[] types = filetype.Split(',');
                foreach (string fileExt in types)
                {
                    if (string.Compare(fileExt, fileExtension.TrimStart('.'), true) == 0)
                    {
                        return true;
                    }
                }
            }
            else
            {
                if (string.Compare(filetype, fileExtension, true) == 0)
                {
                    return true;
                }
            }
            return false;
        }

        protected override void OnInit(EventArgs e)
        {
            if (CurrentUser == null)
            {
                Response.Redirect("~/admin/Login.aspx");
                //Wjtour.Domain.sysadmin user = new Wjtour.Domain.sysadmin();
                //user.adminname = "admin";
                //user.adminpass = Utils.MD5("admin");
                //user.lastloginip = "192.168.1.103";
                //user.lastlogintime = 1;
                //Session["CurrentUser"] = User;
            }

            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (_menus.Count == 0)
            {
                menu_access_bll bll = new menu_access_bll();
                _menus = bll.getMenuList(CurrentUser);
                foreach (var item in _menus)
                {
                    string pagePath = string.Format("{0}/{1}", item.mod, item.act).ToLower();
                    if (item.act.IndexOf('?') > -1
                        && item.act.IndexOf('=') > -1)
                    {
                        string url = item.act.Split('?')[0];
                        string pn = item.act.Split('?')[1].Split('=')[0];
                        string[] pv = item.act.Split('?')[1].Split('=')[1].Split(',');
                        foreach (var pvitem in pv)
                        {
                            string p = string.Format("{0}/{1}?{2}={3}", item.mod, url, pn, pvitem);
                            if (!pathMenuMap.ContainsKey(p))
                            {
                                pathMenuMap.Add(p, item);
                            }
                        }
                    }
                    if (!pathMenuMap.ContainsKey(pagePath))
                    {
                        pathMenuMap.Add(pagePath, item);
                    }
                }
            }
            var master = this.Master as admin;
            if (master != null)
            {
                master.MenuName = CurrentFun.title;
            }
            base.OnLoad(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);


            HtmlLink link = new HtmlLink();

            string script = "\n function redirect(url){\n window.location.href=url;\n}";
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "redirect", script, true);
            script = "\n function parentRedirect(url){\n this.parent.window.location.href=url; \n}";
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "parentRedirect", script, true);
        }

        /// <summary>
        /// 保存操作日志
        /// </summary>
        /// <param name="done"></param>
        internal void SaveLog(string done)
        {
            Wjtour.Domain.adminlog log = new Domain.adminlog();
            log.admin_name = CurrentUser.adminname;
            log.done = CurrentFun.act + "-> " + done;
            log.ip = Utils.GetRealIP();
            log.mod = CurrentFun.mod;
            log.addtime = DateTime.Now;
            new Wjtour.BLL.adminlog_bll().Save(log);
        }

        /// <summary>
        /// 对时间进行转换
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public string ConvertDate(object date)
        {
            if (date == null) return "";
            DateTime dt;
            if (DateTime.TryParse(date.ToString(), out dt))
            {
                return dt.ToString("yyyy-MM-dd");
            }
            return "";
        }


        /// <summary>
        /// 裁剪字符长度
        /// </summary>
        /// <param name="content"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public string CutString(object content, int length)
        {
            if (content == null) return "";
            return Utils.CutString(content.ToString(), 0, length) + "...";
        }

        #region 导出Excel调用区域
        /// <summary>
        /// 输出Exce
        /// </summary>
        /// <param name="resultTable"></param>
        public void OutputExcel(DataTable resultTable)
        {
            string strExcelTempFile = Server.MapPath("/Temp/" + Guid.NewGuid().ToString() + ".xls");
            XlsDocument xls = new XlsDocument();
            Worksheet sheet = xls.Workbook.Worksheets.Add("Sheet1");

            //填充表头  
            foreach (DataColumn col in resultTable.Columns)
            {
                sheet.Cells.Add(1, col.Ordinal + 1, col.ColumnName);
            }

            //填充内容  
            for (int i = 0; i < resultTable.Rows.Count; i++)
            {
                for (int j = 0; j < resultTable.Columns.Count; j++)
                {
                    sheet.Cells.Add(i + 2, j + 1, resultTable.Rows[i][j].ToString());
                }
            }

            //保存  
            xls.FileName = strExcelTempFile;
            xls.Save();

            DownLoadFile(strExcelTempFile, strExcelTempFile);
        }


        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="strPath"></param>
        private void DownLoadFile(string strPath, string strFileName)
        {
            FileInfo file = new FileInfo(strPath);
            if (file.Exists)
            {
                base.Response.Clear();
                base.Response.AddHeader("Content-Length", file.Length.ToString());
                base.Response.Buffer = true;
                base.Response.Charset = "UTF8";
                //string strTemplateName = (string)HttpContext.GetGlobalResourceObject("Vacation", "TemplateName");//模板名
                base.Response.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(strFileName));
                base.Response.ContentEncoding = System.Text.Encoding.UTF8;
                base.Response.ContentType = "application/vnd.ms-excel";
                base.Response.WriteFile(file.FullName);
                base.Response.End();
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "linkExport", "<script>alert(\"下载模板出错\");</script>", false);
            }
        }
        #endregion

        //本地路径转换成URL相对路径
        public string ConvertUrlToRelative(string imagesurl1)
        {
            string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
            string imagesurl2 = imagesurl1.Replace(tmpRootDir, ""); //转换成相对路径
            imagesurl2 = imagesurl2.Replace(@"\", @"/");
            return imagesurl2;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="strPath"></param>
        public void DownLoadFile2(string strPath, string strFileName)
        {
            FileInfo file = new FileInfo(strPath);
            if (file.Exists)
            {
                base.Response.Clear();
                base.Response.AddHeader("Content-Length", file.Length.ToString());
                base.Response.Buffer = true;
                base.Response.Charset = "UTF8";
                base.Response.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(strFileName));
                base.Response.ContentEncoding = System.Text.Encoding.UTF8;
                base.Response.ContentType = "application/octet-stream";
                base.Response.WriteFile(file.FullName);
                base.Response.End();
            }
        }

        public string u(string mod, string act)
        {
            if (string.IsNullOrEmpty(mod))
                return "/admin/article/list.aspx?type=1";
            if (string.IsNullOrEmpty(act))
                return string.Format("admin/{0}/list.aspx", mod);
            return string.Format("/admin/{0}/{1}", mod, act);
        }
    }
}
